<template>
  <div class="address-page">
    <Header :scroll="scroll" />

    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">收货地址管理</h1>
        <p class="page-subtitle">管理您的收货地址信息</p>
      </div>
    </div>

    <!-- 地址内容区域 -->
    <div class="address-content">
      <div class="container">
        <!-- 添加地址按钮 -->
        <div class="add-address-section">
          <button class="add-address-btn" @click="showAddDialog">
            <span class="add-icon">+</span>
            添加新地址
          </button>
        </div>

        <!-- 地址列表 -->
        <div class="address-list" v-infinite-scroll="loadMore" :infinite-scroll-disabled="disabled">
          <div v-for="(address, index) in addressList" :key="address.id" class="address-card" :class="{ default: address.is_default === 1 }">
            <!-- 地址信息 -->
            <div class="address-info" style="cursor: pointer">
              <div class="address-header">
                <div class="recipient-info">
                  <span class="recipient-name">{{ address.realname }}</span>
                  <span class="recipient-phone">{{ proxy.$hidePhoneNumber(proxy.$decryptAES(address.mobile)) }}</span>
                </div>
                <div class="address-tags">
                  <span v-if="address.is_default" class="default-tag">默认</span>
                  <span class="address-tag">{{ getTypeText(address.tag_name) }}</span>
                </div>
              </div>
              <div class="address-detail">
                <p class="address-text">
                  {{ address.province.name + ' ' + address.city.name + ' ' + address.town.name + ' ' + proxy.$decryptAES(address.address) }}
                </p>
              </div>
            </div>

            <!-- 地址操作 -->
            <div class="address-actions">
              <button v-if="address.is_default === 0" class="action-btn default-btn" @click="setDefault(address)">设为默认</button>
              <button class="action-btn edit-btn" @click="editAddress(address)">编辑</button>
              <button class="action-btn delete-btn" @click="deleteAddress(address)">删除</button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="addressList.length === 0" class="empty-state">
          <div class="empty-icon">
            <img src="@/assets/images/cart-green.png" alt="暂无地址" class="empty-image" />
          </div>
          <p class="empty-text">您还没有添加收货地址</p>
          <p class="empty-desc">添加收货地址，让购物更便捷</p>
          <button class="add-first-btn" @click="showAddDialog">添加地址</button>
        </div>
      </div>
    </div>

    <!-- 添加/编辑地址弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑地址' : '添加地址'" width="600px" class="address-dialog">
      <el-form ref="addressFormRef" :model="addressForm" :rules="addressRules" label-width="80px">
        <el-form-item label="收货人" prop="realname">
          <el-input v-model="addressForm.realname" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addressForm.mobile" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            :props="{ value: 'code', label: 'name', checkStrictly: false }"
            placeholder="请选择省市区"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addressForm.address" type="textarea" :rows="3" placeholder="请输入详细地址（街道、门牌号等）" />
        </el-form-item>
        <el-form-item label="地址标签" prop="tag_name">
          <el-radio-group v-model="addressForm.tag_name">
            <el-radio value="home">家</el-radio>
            <el-radio value="company">公司</el-radio>
            <el-radio value="school">学校</el-radio>
            <el-radio value="other">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.is_default" :true-value="1" :false-value="0">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 页脚 -->
    <Footer />
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, reactive, computed, onMounted, watch } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useUserStore } from '@/stores/user.js'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import apiUser from '@/api/modules/user'

  const router = useRouter()
  const route = useRoute()
  const userStore = useUserStore()
  const { proxy } = getCurrentInstance()
  const scroll = ref(false)

  // 监听滚动
  window.addEventListener('scroll', () => {
    scroll.value = window.scrollY > 0
  })

  // 弹窗相关
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const addressFormRef = ref()

  // 地址数据
  const addressList = ref([])
  // 数据分页查询
  const recordCount = ref(0)
  const page = ref(1)
  const limit = ref(6)

  // 是否正在加载
  const loading = ref(false)
  // 是否还有更多数据
  const hasMore = ref(true)
  // 计算属性 - 是否禁用无限滚动
  const disabled = computed(() => loading.value || !hasMore.value)
  // 计算属性 - 是否没有更多数据
  const noMore = computed(() => !hasMore.value && addressList.value.length > 0)

  // 分页加载数据
  const fetchData = async (currentPage) => {
    if (loading.value) {
      return
    }
    loading.value = true
    console.log('分页加载数据', currentPage)
    apiUser
      .GetAddressList({ page: currentPage, limit: limit.value })
      .then(async (res) => {
        loading.value = false
        recordCount.value = res.count
        page.value = currentPage
        hasMore.value = currentPage * limit.value < recordCount.value
        res.data.forEach((item) => {
          item.province = proxy.$parseJsonObject(item.province)
          item.city = proxy.$parseJsonObject(item.city)
          item.town = proxy.$parseJsonObject(item.town)
          item.street = proxy.$parseJsonObject(item.street)
        })
        if (page.value === 1) {
          addressList.value = res.data
        } else {
          addressList.value = [...addressList.value, ...res.data]
        }
      })
      .catch((err) => {
        loading.value = false
      })
  }

  // 加载更多数据
  const loadMore = () => {
    if (!disabled.value) {
      fetchData(page.value + 1)
    }
  }

  // 初始化
  onMounted(() => {
    loadPcsData()
    fetchData(1)
  })

  // 地址表单
  const addressForm = reactive({
    id: '',
    realname: '',
    mobile: '',
    province: {},
    city: {},
    town: {},
    street: {},
    region: [],
    address: '',
    tag_name: 'home',
    is_default: 0,
  })

  // 表单验证规则
  const addressRules = {
    realname: [
      { required: true, message: '请输入收货人姓名', trigger: 'blur' },
      { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' },
    ],
    mobile: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
    ],
    region: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
    address: [
      { required: true, message: '请输入详细地址', trigger: 'blur' },
      { min: 5, max: 100, message: '详细地址长度在 5 到 100 个字符', trigger: 'blur' },
    ],
  }

  // 地区选项（简化版，实际项目中应该从API获取）
  const regionOptions = ref([])
  const loadPcsData = () => {
    fetch(proxy.$buildUrl('/static/json/pcs-code.json'))
      .then((response) => response.json())
      .then((data) => {
        regionOptions.value = data
      })
  }

  // 显示添加地址弹窗
  const showAddDialog = () => {
    isEdit.value = false
    resetForm()
    dialogVisible.value = true
  }

  // 编辑地址
  const editAddress = (address) => {
    isEdit.value = true

    // 查找省份索引
    const provinceIndex = regionOptions.value.findIndex((p) => p.name === address.province.name)

    // 查找城市索引
    const province = regionOptions.value[provinceIndex]
    const cityIndex = province.children.findIndex((c) => c.name === address.city.name)

    // 查找区县索引
    const city = province.children[cityIndex]
    const areaIndex = city?.children.findIndex((a) => a.name === address.town.name)

    addressForm.id = address.id
    addressForm.realname = address.realname
    addressForm.mobile = proxy.$decryptAES(address.mobile)
    if (provinceIndex >= 0 && cityIndex >= 0) {
      addressForm.region = [address.province.code, address.city.code, address.town.code]
    } else {
      addressForm.region = []
    }
    addressForm.address = proxy.$decryptAES(address.address)
    addressForm.tag_name = address.tag_name
    addressForm.is_default = address.is_default
    dialogVisible.value = true
  }

  // 重置表单
  const resetForm = () => {
    addressForm.id = null
    addressForm.realname = ''
    addressForm.mobile = ''
    addressForm.region = []
    addressForm.address = ''
    addressForm.tag_name = 'home'
    addressForm.is_default = false
  }

  // 保存地址
  const saveAddress = async () => {
    try {
      await addressFormRef.value.validate()

      // region ['11', '1101', '110101']
      const province_code = addressForm.region[0]
      const city_code = addressForm.region[1]
      const town_code = addressForm.region[2]
      // 查找省份索引
      const provinceIndex = regionOptions.value.findIndex((p) => p.code === province_code)
      // 查找城市索引
      const province = regionOptions.value[provinceIndex]
      const cityIndex = province.children.findIndex((c) => c.code === city_code)
      // 查找区县索引
      const city = province.children[cityIndex]
      const areaIndex = city?.children.findIndex((a) => a.code === town_code)

      addressForm.province = {
        code: province_code,
        name: provinceIndex >= 0 ? regionOptions.value[provinceIndex].name : '',
      }
      addressForm.city = {
        code: city_code,
        name: cityIndex >= 0 ? province.children[cityIndex].name : '',
      }
      addressForm.town = {
        code: town_code,
        name: areaIndex >= 0 ? city.children[areaIndex].name : '',
      }

      apiUser.SaveAddress(addressForm).then(async (res) => {
        if (isEdit.value) {
          // 编辑地址
          const index = addressList.value.findIndex((addr) => addr.id === addressForm.id)
          if (index !== -1) {
            let saveAddressForm = { ...addressForm }
            saveAddressForm.mobile = proxy.$encryptAES(saveAddressForm.mobile)
            saveAddressForm.address = proxy.$encryptAES(saveAddressForm.address)
            addressList.value[index] = saveAddressForm
          }
          ElMessage.success('地址修改成功')
        } else {
          // 添加地址
          fetchData(1)
          ElMessage.success('地址添加成功')
        }

        // 如果设置为默认地址，取消其他地址的默认状态
        if (addressForm.is_default === 1) {
          addressList.value.forEach((addr) => {
            if (addr.id !== addressForm.id) {
              addr.is_default = 0
            }
          })
        }

        dialogVisible.value = false
      })
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }

  // 设为默认地址
  const setDefault = (address) => {
    if (address.is_default === 1) return
    apiUser.SetDefaultAddress({ id: address.id }).then(async (res) => {
      addressList.value.forEach((addr) => {
        addr.is_default = addr.id === address.id ? 1 : 0
      })
      ElMessage.success('默认地址设置成功')
    })
  }

  // 删除地址
  const deleteAddress = (address) => {
    ElMessageBox.confirm('确定要删除这个地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        apiUser.DelAddress({ id: address.id }).then(async (res) => {
          const index = addressList.value.findIndex((addr) => addr.id === address.id)
          if (index !== -1) {
            addressList.value.splice(index, 1)
            ElMessage.success('地址删除成功')
          }
        })
      })
      .catch(() => {
        // 用户取消删除
      })
  }

  // 获取状态标识
  const getTypeText = (type) => {
    const statusMap = {
      home: '家',
      company: '公司',
      school: '学校',
      other: '其他',
    }
    return statusMap[type] || '其他'
  }
</script>

<style scoped>
  .address-page {
    width: 100%;
    min-height: 100vh;
    background-color: #ffffff;
  }

  /* 页面标题区域 */
  .page-header {
    background: linear-gradient(135deg, #52a58a 0%, #459a7e 100%);
    padding: 60px 0;
    color: white;
    text-align: center;
  }

  .page-title {
    font-size: 32px;
    font-weight: 600;
    margin: 0 0 15px 0;
  }

  .page-subtitle {
    font-size: 16px;
    margin: 0;
    opacity: 0.9;
  }

  /* 地址内容区域 */
  .address-content {
    padding: 40px 0;
  }

  /* 添加地址按钮区域 */
  .add-address-section {
    margin-bottom: 30px;
    text-align: center;
  }

  .add-address-btn {
    background: #52a58a;
    color: white;
    border: none;
    padding: 15px 30px;
    border-radius: 25px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 8px;
  }

  .add-address-btn:hover {
    background: #459a7e;
    transform: translateY(-2px);
  }

  .add-icon {
    font-size: 20px;
    font-weight: bold;
  }

  /* 地址列表 */
  .address-list {
    display: grid;
    gap: 20px;
  }

  /* 地址卡片 */
  .address-card {
    background: white;
    border-radius: 12px;
    padding: 25px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    position: relative;
  }

  .address-card:hover {
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
  }

  .address-card.default {
    border: 2px solid #52a58a;
  }

  .address-card.default::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #52a58a 0%, #459a7e 100%);
    border-radius: 12px 12px 0 0;
  }

  /* 地址信息 */
  .address-info {
    margin-bottom: 20px;
  }

  .address-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 15px;
  }

  .recipient-info {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .recipient-name {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .recipient-phone {
    font-size: 16px;
    color: #666;
  }

  .address-tags {
    display: flex;
    gap: 8px;
  }

  .default-tag {
    background: #52a58a;
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
  }

  .address-tag {
    background: #f0f0f0;
    color: #666;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
  }

  .address-detail {
    margin-top: 10px;
  }

  .address-text {
    font-size: 15px;
    color: #555;
    line-height: 1.5;
    margin: 0;
  }

  /* 地址操作 */
  .address-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }

  .action-btn {
    padding: 8px 16px;
    border: 1px solid #ddd;
    border-radius: 20px;
    background: white;
    color: #666;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .action-btn:hover {
    transform: translateY(-1px);
  }

  .default-btn {
    border-color: #52a58a;
    color: #52a58a;
  }

  .default-btn:hover {
    background: #52a58a;
    color: white;
  }

  .edit-btn:hover {
    border-color: #1890ff;
    color: #1890ff;
  }

  .delete-btn:hover {
    border-color: #e53935;
    color: #e53935;
  }

  /* 空状态 */
  .empty-state {
    text-align: center;
    padding: 80px 20px;
  }

  .empty-icon {
    margin-bottom: 30px;
  }

  .empty-image {
    width: 120px;
    height: 120px;
    opacity: 0.3;
  }

  .empty-text {
    font-size: 18px;
    color: #333;
    margin-bottom: 10px;
  }

  .empty-desc {
    font-size: 14px;
    color: #999;
    margin-bottom: 30px;
  }

  .add-first-btn {
    background: #52a58a;
    color: white;
    border: none;
    padding: 12px 30px;
    border-radius: 25px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  .add-first-btn:hover {
    background: #459a7e;
  }

  /* 弹窗样式 */
  :deep(.address-dialog) {
    .el-dialog__header {
      background: #f8f9fa;
      padding: 20px 25px;
      margin: 0;
    }

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .el-dialog__body {
      padding: 25px;
    }

    .el-dialog__footer {
      padding: 20px 25px;
      background: #f8f9fa;
    }

    .el-button--primary {
      background: #52a58a;
      border-color: #52a58a;
    }

    .el-button--primary:hover {
      background: #459a7e;
      border-color: #459a7e;
    }
  }

  /* 响应式设计 */
  @media (max-width: 1024px) {
    .address-content {
      padding: 30px 0;
    }

    .address-card {
      padding: 20px;
    }

    .recipient-info {
      gap: 12px;
    }

    .recipient-name {
      font-size: 17px;
    }

    .recipient-phone {
      font-size: 15px;
    }
  }

  @media (max-width: 768px) {
    .page-header {
      padding: 40px 0;
    }

    .page-title {
      font-size: 24px;
    }

    .page-subtitle {
      font-size: 14px;
    }

    .address-content {
      padding: 30px 0;
    }

    .add-address-section {
      margin-bottom: 25px;
      padding: 0 20px;
    }

    .add-address-btn {
      padding: 12px 25px;
      font-size: 15px;
    }

    .address-list {
      gap: 15px;
      padding: 0 20px;
    }

    .address-card {
      padding: 20px;
    }

    .address-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
    }

    .recipient-info {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
      width: 100%;
    }

    .recipient-name {
      font-size: 16px;
    }

    .recipient-phone {
      font-size: 14px;
    }

    .address-tags {
      align-self: flex-end;
    }

    .address-text {
      font-size: 14px;
    }

    .address-actions {
      flex-wrap: wrap;
      gap: 8px;
      justify-content: flex-start;
    }

    .action-btn {
      flex: 1;
      min-width: calc(33.333% - 6px);
      text-align: center;
      padding: 10px 12px;
      font-size: 13px;
    }

    .empty-state {
      padding: 60px 15px;
    }

    .empty-image {
      width: 100px;
      height: 100px;
    }

    /* 弹窗移动端适配 */
    :deep(.address-dialog) {
      .el-dialog {
        width: 90% !important;
        margin: 5vh auto !important;
      }

      .el-dialog__body {
        padding: 20px;
      }

      .el-form-item__label {
        font-size: 14px;
      }

      .el-input__inner,
      .el-textarea__inner {
        font-size: 14px;
      }

      .el-cascader {
        width: 100%;
      }

      .el-radio {
        margin-right: 15px;
        margin-bottom: 10px;
      }

      .el-radio__label {
        font-size: 14px;
      }

      .dialog-footer {
        display: flex;
        gap: 10px;
      }

      .el-button {
        flex: 1;
      }
    }
  }

  @media (max-width: 480px) {
    .page-header {
      padding: 30px 0;
    }

    .page-title {
      font-size: 20px;
    }

    .page-subtitle {
      font-size: 13px;
    }

    .address-content {
      padding: 20px 0;
    }

    .add-address-section {
      padding: 0 15px;
    }

    .add-address-btn {
      padding: 10px 20px;
      font-size: 14px;
    }

    .address-list {
      padding: 0 15px;
      gap: 12px;
    }

    .address-card {
      padding: 15px;
    }

    .recipient-name {
      font-size: 15px;
    }

    .recipient-phone {
      font-size: 13px;
    }

    .default-tag,
    .address-tag {
      font-size: 11px;
      padding: 3px 6px;
    }

    .address-text {
      font-size: 13px;
    }

    .address-actions {
      gap: 6px;
    }

    .action-btn {
      padding: 8px 10px;
      font-size: 12px;
      border-radius: 15px;
    }

    .empty-state {
      padding: 40px 10px;
    }

    .empty-text {
      font-size: 16px;
    }

    .empty-desc {
      font-size: 13px;
    }

    .add-first-btn {
      padding: 10px 25px;
      font-size: 14px;
    }

    /* 弹窗超小屏适配 */
    :deep(.address-dialog) {
      .el-dialog {
        width: 95% !important;
        margin: 2vh auto !important;
      }

      .el-dialog__header {
        padding: 15px 20px;
      }

      .el-dialog__title {
        font-size: 16px;
      }

      .el-dialog__body {
        padding: 15px;
      }

      .el-form-item {
        margin-bottom: 18px;
      }

      .el-form-item__label {
        font-size: 13px;
        line-height: 1.4;
      }

      .el-input__inner,
      .el-textarea__inner {
        font-size: 13px;
      }

      .el-radio {
        margin-right: 12px;
        margin-bottom: 8px;
      }

      .el-radio__label {
        font-size: 13px;
      }

      .el-checkbox__label {
        font-size: 13px;
      }

      .dialog-footer {
        padding: 15px 20px;
      }

      .el-button {
        padding: 8px 15px;
        font-size: 13px;
      }
    }
  }
</style>
